package com.gict.antifraudback.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gict.antifraudback.entity.Article;
import com.gict.antifraudback.entity.Files;
import com.gict.antifraudback.entity.Menu;
import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.service.ArticleService;
import com.gict.antifraudback.service.FilesService;
import com.gict.antifraudback.mapper.FilesMapper;
import com.gict.antifraudback.service.MenuService;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.oss.TencentOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author XIE
* @description 针对表【files(存储文件信息的表)】的数据库操作Service实现
* @createDate 2023-11-01 19:48:04
*/
@Service
public class FilesServiceImpl extends ServiceImpl<FilesMapper, Files>
    implements FilesService{

    @Value("${image.upload.path}")
    private String uploadPath; // 保存路径
    @Value("${file.visit.path}")
    private String visitPath; // 访问路径
    @Autowired
    private ArticleService articleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private TencentOssUtil tencentOssUtil;

    @Override
    public String uploadFile(MultipartFile image, String label) {
        if (image.isEmpty()) {
            throw new MyException("文件为空！");
        }
        // 先判断父文件夹
        File parentPath = new File(uploadPath);
        if (!parentPath.exists()) {
            parentPath.mkdirs();
        }

        // 创建子文件夹，以标签文件夹名称
        File folder = new File(uploadPath, label);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 获取今天的时间,每天创建一个文件夹
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String folderName = dateFormat.format(new Date());
        File folderFile = new File(uploadPath + label, folderName);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        // 生成唯一的文件名
        String uniqueFileName = UUID.randomUUID().toString().replaceAll("-", "") + image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("\\.") + 1);

        // 保存文件
        try {
            File file = new File(folderFile.getAbsolutePath() + "/" + uniqueFileName);
            image.transferTo(file);

            // 保存数据库
            Files files = new Files();
            files.setFilePath(file.getAbsolutePath());
            files.setLabel(label);
            files.setAccessPath(visitPath + label + "/" + folderName + "/" + uniqueFileName);

            save(files);

            return files.getAccessPath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String uploadFileToOss(MultipartFile image, String label) {
        String uniqueFileName = UUID.randomUUID().toString().replaceAll("-", "") + Objects.requireNonNull(image.getOriginalFilename()).substring(image.getOriginalFilename().lastIndexOf("\\.") + 1);
        Map<String, String> result = tencentOssUtil.uploadFileToCOS(image, uniqueFileName);

        return saveToDb(label, result);
    }

    @Override
    public String uploadFileToOss(File image, String label) {
        String uniqueFileName = UUID.randomUUID().toString().replaceAll("-", "") + Objects.requireNonNull(image.getName()).substring(image.getName().lastIndexOf("\\.") + 1);
        Map<String, String> result = tencentOssUtil.putLocalFile(uniqueFileName, image);

        return saveToDb(label, result);
    }

    private String saveToDb(String label, Map<String, String> result) {
        String url = result.get("url");
        String eTag = result.get("ETag");
        String requestId = result.get("requestId");
        if (!ObjectUtils.isEmpty(url)) {
            // 保存数据库
            Files files = new Files();
            files.setFilePath("腾讯云cos");
            files.setLabel(label);
            files.setETag(eTag);
            files.setRequestId(requestId);
            files.setAccessPath(url);

            save(files);
        }else {
            throw new MyException("上传文件失败");
        }

        return url;
    }

    @Override
    public String dataRepair() {
        String fix = "http://xhtlove.cn/";
        String replace = "C:/Users/xie/Desktop/";

        // 修复文章
        List<Article> list = articleService.list();
        for (Article article : list) {
            String articleCover = article.getArticleCover();
            if (!ObjectUtils.isEmpty(articleCover)){
                articleCover = articleCover.replace(fix, replace);
                String[] split = articleCover.split("/");

                articleCover = uploadFileToOss(new File(articleCover), split[split.length - 1]);
                article.setArticleCover(articleCover);
                articleService.updateById(article);
            }
        }
        // 修复菜单
        List<Menu> menuList = menuService.list();
        for (Menu menu : menuList) {
            String pic = menu.getPic();
            if (!ObjectUtils.isEmpty(pic)){
                pic = pic.replace(fix, replace);
                String[] split = pic.split("/");

                pic = uploadFileToOss(new File(pic), split[split.length - 1]);
                menu.setPic(pic);
                menuService.updateById(menu);
            }
        }
        // 修复用户
        List<User> userList = userService.list();
        for (User user : userList) {
            String avatar = user.getAvatar();
            if (!ObjectUtils.isEmpty(avatar)){
                avatar = avatar.replace(fix, replace);
                String[] split = avatar.split("/");

                avatar = uploadFileToOss(new File(avatar), split[split.length - 1]);
                user.setAvatar(avatar);
                userService.updateById(user);
            }
        }

        return "";
    }
}




